/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package bpmlab.shift.dao;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;

/**
 *
 * @author Simeia Lima
 */
public class JpaUtil {

    private static final String PERSISTENCE_UNIT = "bpmlab_SHIFT_war_1.0-SNAPSHOTPU";

    private static EntityManagerFactory entityManagerFactory;
    private static ThreadLocal<EntityManager> threadEntityManager;

    private JpaUtil() {
    }

    public static void init() {
        entityManagerFactory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT);
    }

    public static EntityManager getEntityManager() {
        if (threadEntityManager == null) {
            threadEntityManager = new ThreadLocal<>();
        }
        EntityManager entityManager = threadEntityManager.get();
        if (entityManager == null || !entityManager.isOpen()) {
            entityManager = entityManagerFactory.createEntityManager();
            threadEntityManager.set(entityManager);
        }
        return entityManager;
    }

    public static void closeEntityManager() {
        EntityManager entityManager = threadEntityManager.get();
        if (entityManager != null) {
            EntityTransaction entityTransaction = entityManager.getTransaction();
            if (entityTransaction.isActive()) {
                entityTransaction.commit();
            }
            entityManager.close();
            threadEntityManager.set(null);
        }
    }

    public static void closeEntityManagerFactory() {
        closeEntityManager();
        entityManagerFactory.close();
    }
}
